package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.*;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Resource
    private SetmealDao setmealDao;
    @Resource
    private Setmeal_CheckgroupDao setmeal_checkgroupDao;
    @Resource
    private CheckgroupDao checkgroupDao;
    @Resource
    private Checkgroup_CheckitemDao checkgroup_checkitemDao;
    @Resource
    private CheckItemDao checkItemDao;

    @Override
    public PageResult SelectPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.SelectPage(queryPageBean.getQueryString());
        return PageResult.builder().rows(page.getResult()).total(page.getTotal()).build();
    }

    @Transactional
    @Override
    public void Add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.Add(setmeal);
        if (checkgroupIds == null) {
            throw new BusinessRuntimeException(MessageConst.ADD_SETMEAL_FAIL);
        }
        setmeal_checkgroupDao.Add(setmeal.getId(), checkgroupIds);

    }

    @Override
    public List<Setmeal> getMeal() {
        return setmealDao.getMeal();
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        List<CheckGroup> checkGroupList = checkgroupDao.SelectById(setmeal_checkgroupDao.SelectBySetmealId(setmeal.getId()));
        setmeal.setCheckGroups(checkGroupList);
        for (CheckGroup group : checkGroupList) {
            List<CheckItem> checkItemList = checkItemDao.findCheckItemIdsByCheckGroupId(checkgroup_checkitemDao.findCheckItemIdsByCheckGroupId(group.getId()));
            group.setCheckItems(checkItemList);
        }
        return setmeal;
    }
}
